package com.athl.demoreactor.handler;

import com.athl.demoreactor.entity.User;
import com.athl.demoreactor.service.UserService;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import static org.springframework.web.reactive.function.BodyInserters.fromValue;

/**
 * @author hl
 * @Data 2020/9/16
 */
public class UserHandler {

    private final UserService userService;

    public UserHandler(UserService userService) {
        this.userService = userService;
    }

    /**
     * 根据id查询
     *
     * @param request
     * @return
     */
    public Mono<ServerResponse> getUserById(ServerRequest request) {
        Integer userId = Integer.valueOf(request.pathVariable("id"));
        Mono<User> userMono = this.userService.getUserById(userId);
        // 空值处理
        Mono<ServerResponse> noFind = ServerResponse.notFound().build();

        return userMono.flatMap((user -> {
            return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(fromValue(user)).switchIfEmpty(noFind);
        }));
    }

    /**
     * 查询所有
     *
     * @return
     */
    public Mono<ServerResponse> getAllUser(ServerRequest serverRequest) {
        Flux<User> allUser = this.userService.getAllUser();

        // 空值处理
        Mono<ServerResponse> noFind = ServerResponse.notFound().build();

        return ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(allUser, User.class).switchIfEmpty(noFind);
    }

    /**
     * 保存user
     */
    public Mono<ServerResponse> saveUser(ServerRequest request) {
        Mono<User> userMono = request.bodyToMono(User.class);

        return ServerResponse.ok().build(this.userService.saveUserInfo(userMono));
    }
}
